package com.mytijian.openapi.adapter.alihalt;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSON;
import com.mytijian.code.dto.QueryItemIdByCodeResult;
import com.mytijian.code.param.alihalt.QueryItemIdByCodeParam;
import com.mytijian.code.service.MerchantService;
import com.mytijian.openapi.adapter.alihalt.consts.AlihaltConsts;
import com.mytijian.openapi.adapter.alihalt.exception.AlihaltException;
import com.mytijian.openapi.adapter.alihalt.model.McodeInfo;
import com.mytijian.openapi.core.client.OpenAPIClient;
import com.mytijian.openapi.core.client.result.MealInfo;
import com.mytijian.openapi.core.model.AppConfig;
import com.mytijian.openapi.core.service.OpenApiAppConfigService;

@Component
public class AlihaltMcodeHelper {
	
	private Logger log = LoggerFactory.getLogger(getClass());

	
	@Autowired
	private MerchantService merchantService;
	
	@Autowired
	private OpenAPIClient client;
	
	@Autowired
	private OpenApiAppConfigService openAPIService;
	
	public McodeInfo getMealId(String mcode) {
		McodeInfo info = new McodeInfo();
		
		String tmallProductId = getTmallProductId(mcode);
		info.setRefTmallProductId(tmallProductId);
		
		AppConfig config = openAPIService.getConfig(AlihaltConsts.AppName);
		MealInfo meal = client.getMealByTmallProductId(config, tmallProductId);
		
		verifyMeal(meal);
		
		if (!verifyMeal(meal)) {
			log.error("[阿里健康] [套餐查询] OpenAPI 调用失败。 接口返回参数: {}", JSON.toJSONString(meal));
			throw new AlihaltException("500", "套餐查询错误");
		}
		
		info.setRefHospitalId(meal.getHospitalId());
		info.setRefMealId(meal.getMealId());
		return info;
	}

	private boolean verifyMeal(MealInfo meal) {
		if (meal == null) {
			return false;
		}

		if (StringUtils.isNotEmpty(meal.getErrCode())) {
			return false;
		}

		if (meal.getMealId() == null) {
			return false;
		}

		return true;
	}
	
	private String getTmallProductId(String mcode) {
		QueryItemIdByCodeParam qp = new QueryItemIdByCodeParam();
		qp.setCode(mcode);
		QueryItemIdByCodeResult tmprod = null;

		try {
			tmprod = merchantService.queryItemIdByCode(qp);
		} catch (RuntimeException e) {
			throw new AlihaltException("400", e.getMessage());
		}

		if (tmprod == null || StringUtils.isEmpty(tmprod.getItemId())) {
			throw new AlihaltException("400", "电子码无效");
		}

		String tmallProductId = tmprod.getItemId();
		return tmallProductId;
	}
}
